<?php
/*
 * Mysql数据库连接单例类MysqlConn
 */
class MysqlConn {
	private static $instance;
	private $conn=null;
    protected function __construct() 
	{
		$options = DBConfig::getConfig();
		//如果$options为空，则抛出异常，也可不处理
		foreach($options as $k=>$val){
			$$k = $val;
		}
		$this->conn = $this->connect($dbhost, $dbuser, $dbpw, $dbname , $charset, $pconnect=0 );
	}
	 public static function getInstance() { 
        if (!is_object(self::$instance)) { 
			$self = __CLASS__;//php5.3中get_called_class()解决了__CLASS__在继承中的问题
            self::$instance = new $self(); 
        } 
        return self::$instance; 
    } 
	private function connect($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf-8',$pconnect = 0)
	{
		$func = $pconnect == 1 ? 'mysql_pconnect' : 'mysql_connect';
		if(!$this->conn = @$func($dbhost, $dbuser, $dbpw))
		{
			//$this->message('Can not connect to MySQL server');
			return false;
		}
		if($this->version() > '4.1')
		{
			$serverset = $charset ? "character_set_connection='$charset',character_set_results='$charset',character_set_client=binary" : '';
			$serverset .= $this->version() > '5.0.1' ? ((empty($serverset) ? '' : ',')." sql_mode='' ") : '';
			$serverset && mysql_query("SET $serverset", $this->conn);
		}
		if($dbname && !@mysql_select_db($dbname , $this->conn))
		{
			//$this->message('Cannot use database '.$dbname);
			return false;
		}
		$this->dbname = $dbname;
		return $this->conn;
	}
	public function __get($field)
	{
		if($field == 'conn') return $this->conn;
		else return null;
	}
	public function version()
	{
		return mysql_get_server_info($this->conn);
	}
}  

?>
